package com.vtech.mybatis.baseservice.plugins;

import com.google.common.base.CaseFormat;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.config.TableConfiguration;

import java.util.List;

/**
 * 类的别名
 * <p>https://github.com/mybatis/generator/issues/42
 *
 * @author houzhiwei
 * @date 2018/12/4 10:59
 */
public class TypeAliasPlugin extends PluginAdapter {

    private FullyQualifiedJavaType typeAlias;

    public TypeAliasPlugin() {
        super();
        typeAlias = new FullyQualifiedJavaType("org.apache.ibatis.type.Alias");
    }

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
                                                 IntrospectedTable introspectedTable) {
        addTypeAlias(topLevelClass, introspectedTable);
        return true;
    }

    private void addTypeAlias(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        topLevelClass.addImportedType(typeAlias);

        TableConfiguration tableConfiguration = introspectedTable.getTableConfiguration();
        String domainObjectName = tableConfiguration.getDomainObjectName();
        String tableAlias = tableConfiguration.getTableName().replaceFirst("t_", "");
        // 首字母大写，驼峰命名
        tableAlias = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableAlias);
        String alias = domainObjectName == null ? tableAlias : domainObjectName;
        String aliasAnnotation = String.format("@Alias(\"%s\")", alias);
        topLevelClass.addAnnotation(aliasAnnotation);
    }
}
